<template>
  <el-form
      ref="ruleFormRef"
      :model="loginForm"
      :rules="rules"
  >
    <el-form-item prop="account">
      <el-input v-model="loginForm.account" placeholder="请输入账号"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
    </el-form-item>
  </el-form>
  <el-button @click="submitForm(ruleFormRef)" type="primary" class="w-full mb-4">登录</el-button>
  <el-button @click="router.push({name:'register'})" type="primary" style="margin-left: 0px" class="w-full" plain>还没有账号？去注册！→</el-button>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import {useRouter} from "vue-router";
import {login} from "@/api/user";
import {ElMessage} from "element-plus";
import cookie from "js-cookie"
import {compareInfo, hashInfo} from "@/utils/hash";
import bcrypt from "bcryptjs";

const router = useRouter()
const ruleFormRef = ref<FormInstance>()

const validateAccount = (rule: any, value: any, callback: any) => {
  if (loginForm.account === '') {
    callback(new Error('请输入账号'))
  } else {
    callback()
  }
}
const validatePassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (loginForm.password !== "1111") {
    callback(new Error("密码错误"))
  } else {
    callback()
  }
}

const loginForm = reactive({
  account:"YuanJiu",
  password:"74375625Sh",
})

const rules = reactive<FormRules>({
  account: [{ validator: validateAccount, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  // 提交前的表单验证
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!')
    } else {
      console.log('error submit!')
      return false
    }
  })

  //前端加密
  // for (const key in loginForm) {
  //   loginForm[key] = hashInfo(loginForm[key])
  // }

  login(loginForm).then(res=>{
    if (compareInfo(loginForm.password, res.data.user.password)){
      //从后端获取token并存储在cookie中
      cookie.set("Admin-Token",res.data.token)
      router.push({path:"/home/homePage"})
      ElMessage.success("登录成功")
    }else {
      ElMessage.error("密码错误");
    }
    //清空表单数据
    for (const key in loginForm) {
      loginForm[key] = "";
    }
  },err=>{
    console.log("登录接口:" + err);
  })
}
</script>

<style scoped>

</style>
